package com.yesjpt.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import com.alibaba.fastjson2.JSONObject;

//WebSocketClient连接
public class WebSocketConn {// websocket建立连接
	public WebSocketClient Connect(String wsUrl) {
		try {
			WebSocketClient client = new WebSocketClient(new URI(wsUrl)) {
				// 打开链接
				@Override
				public void onOpen(ServerHandshake shake) {
					System.out.println("握手。。。");
				}
				@Override
				public void onMessage(String msgString) {
					System.out.println("websocket返回消息" + msgString);
				}
				// 客户端发生错误,即将关闭!
				@Override
				public void onError(Exception e) {
					System.out.println("发生错误已关闭");
					e.printStackTrace();
				}
				// 关闭链接
				@Override
				public void onClose(int arg0, String arg1, boolean arg2) {
					System.out.println("连接已关闭， arg1 = " + arg1);
				}
			};
			client.connect();
			int i = 0;
			while (!client.getReadyState().equals(ReadyState.OPEN)) {
				try {
					Thread.sleep(2000);//相当重要
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				i += 1;
				if (i > 5) {
					L.i("连接建立失败，那边末得回应！");
					client.close();
					return null;
				}
				L.i("正在进行第 " + i + "次连接...");
			}
			System.out.println("成功建立websocket连接");
			return client;
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 关闭websocket连接
	public void closeWebSocket(HttpServletRequest request) {
		HttpSession session = request.getSession();
		WebSocketClient client = (WebSocketClient) session.getAttribute(" client");
		client.close();
		System.out.println("websocket主动关闭！");
	}

	public static void main(String[] arg0) throws Exception {
		WebSocketConn conn = new WebSocketConn();
		//WebSocketClient client = conn.Connect("ws://47.95.202.29:8081/websocket/" + URLEncoder.encode("测试的话痨甲", "utf-8"));
		WebSocketClient client = conn.Connect("ws://localhost:8081/websocket/" + URLEncoder.encode("测试的话痨甲", "utf-8"));
		if(client != null && client.getReadyState().equals(ReadyState.OPEN)) {
			L.i("正在发送消息。。。");
			JSONObject o = new JSONObject();
			o.put("cid", "laochen");
			o.put("toCid", "测试的话痨甲");
			o.put("message", "太好了");
			client.send(o.toJSONString());
			//休息一下等消息过来再关
			Thread.sleep(10000);
			client.close();
		}
	}
}






















